// Promise 版本 post
function postPro (options) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest()
    xhr.open('post', options.url)
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(xhr.responseText)
        } else {
          reject(xhr.responseText)
        }
      }
    }
    if (options.params) {
      let str = ''
      for (let key in options.params) {
        str += `${key}=${options.params[key]}`
        str += '&'
      }
      str = str.slice(0, -1)
      xhr.send(str)
    } else {
      xhr.send()
    }
  })
}
// Promise 版本 post token
function postProToken (options) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest()
    xhr.open('post', options.url)
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    xhr.setRequestHeader("authorization", options.token)
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(xhr.responseText)
        } else {
          reject(xhr.responseText)
        }
      }
    }
    if (options.params) {
      let str = ''
      for (let key in options.params) {
        str += `${key}=${options.params[key]}`
        str += '&'
      }
      str = str.slice(0, -1)
      xhr.send(str)
    } else {
      xhr.send()
    }
  })
}
// Promise版本ajax  get
function getPro (options) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest()
    if (options.params) {
      let str = '?'
      for (let key in options.params) {
        str += `${key}=${options.params[key]}`
        str += '&'
      }
      str = str.slice(0, -1)
      xhr.open('get', options.url + str, true)
    } else {
      xhr.open('get', options.url, true)
    }
    xhr.setRequestHeader("authorization", options.token)
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(xhr.responseText)
        } else {
          reject()
        }
      }
    }
    xhr.send()
  })
}
export default { getPro, postProToken, postPro }